package com.ly.web.controller.admin;

import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.ly.base.ApiDataTableResponse;
import com.ly.base.ApiResponse;
import com.ly.base.HouseOperation;
import com.ly.base.HouseStatus;
import com.ly.entity.SupportAddress;
import com.ly.service.IUserService;
import com.ly.service.ServiceMultiResult;
import com.ly.service.ServiceResult;
import com.ly.service.house.IAddressService;
import com.ly.service.house.IHouseService;
import com.ly.service.house.IQiNiuService;
import com.ly.service.search.ISearchService;
import com.ly.web.dto.*;
import com.ly.web.form.DatatableSearch;
import com.ly.web.form.DatatableUserSearch;
import com.ly.web.form.HouseForm;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Pair;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 管理员接口
 * @author ：LY
 * @date ：Created in 2020/11/8 17:35
 * @modified By：
 */
@Controller
public class AdminController {
    @Autowired
    private IQiNiuService iQiNiuService;

    @Autowired
    private IAddressService addressService;

    @Autowired
    private IHouseService iHouseService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ISearchService searchService;

    @Autowired
    private Gson gson;
    /**
     * 后台管理中心
     * @return
     */
    @GetMapping("/admin/center")
    public String adminCenterPage(){
        return "admin/center";
    }
    /**
     * 欢迎页
     * @return
     */
    @GetMapping("/admin/welcome")
    public String welcomePage(){
        return "admin/welcome";
    }
    /**
     * 管理员登录页
     * @return
     */
    @GetMapping("/admin/login")
    public String adminLogPage(){
        return "admin/login";
    }
    /**
     * 新增房源功能页
     * @return
     */
    @GetMapping("/admin/add/house")
    public String addHousePage(){
        return "admin/house-add";
    }
    /**
     * 房源列表页
     * @return
     */
    @GetMapping("admin/house/list")
    public String houseListPage() {
        return "admin/house-list";
    }

    @GetMapping("admin/user/list")
    public String userListPage() {
        return "admin/user-list";
    }
    /**
     * 房源浏览页搜索功能接口
     * @param searchBody
     * @return
     */
    @PostMapping("admin/houses")
    @ResponseBody
    public ApiResponse houses(@ModelAttribute DatatableSearch searchBody){

        ServiceMultiResult<HouseDTO> result = iHouseService.adminQuery(searchBody);
        ApiDataTableResponse response = new ApiDataTableResponse(ApiResponse.Status.SUCCESS);
        response.setData(result.getResult());
        response.setRecordsFiltered(result.getTotal());
        response.setRecordsTotal(result.getTotal());
        //回显
        response.setDraw(searchBody.getDraw());
        return response;
    }
    @PostMapping("admin/users")
    @ResponseBody
    public ApiResponse users(@ModelAttribute DatatableUserSearch datatableUserSearch){

        ServiceMultiResult<UserDTO> userDTOServiceMultiResult = userService.adminUserQuery(datatableUserSearch);
        ApiDataTableResponse response = new ApiDataTableResponse(ApiResponse.Status.SUCCESS);
        response.setData(userDTOServiceMultiResult.getResult());
        response.setRecordsFiltered(userDTOServiceMultiResult.getTotal());
        response.setRecordsTotal(userDTOServiceMultiResult.getTotal());
        //回显
        response.setDraw(datatableUserSearch.getDraw());
        return response;
    }
    /**
     * 图片上传接口
     * @ResponseBody 让方法成为一个API
     * @param file
     * @return
     */
    @PostMapping(value = "admin/upload/photo",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public ApiResponse uploadPhoto(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return ApiResponse.ofStatus(ApiResponse.Status.NOT_VALID_PARAM);
        }
        String filename = file.getOriginalFilename();

        try {
            //获取图片字节流
            InputStream inputStream = file.getInputStream();
            //调用方法以字节流方式将图片上传至七牛云
            Response response = iQiNiuService.uploadFile(inputStream);

            if (response.isOK()){
                //上传成功就将信息响应给前端
                QiNiuPutRet qiNiuPutRet = gson.fromJson(response.bodyString(), QiNiuPutRet.class);
                return ApiResponse.ofSuccess(qiNiuPutRet);
            }else {
                return ApiResponse.ofMessage(response.statusCode,response.getInfo());
            }
        }catch (QiniuException e){
            //处理七牛云异常
            Response response  = e.response;
            try {
                return ApiResponse.ofMessage(response.statusCode,response.bodyString());
            } catch (QiniuException qiniuException) {
                qiniuException.printStackTrace();
                return ApiResponse.ofStatus(ApiResponse.Status.INTERNAL_SERVER_ERROR);
            }

        }catch (IOException e) {
            return ApiResponse.ofStatus(ApiResponse.Status.INTERNAL_SERVER_ERROR);
        }

//        File target = new File("C:/Users/ly/IdeaProjects/xunwu_ly/temp/"+filename);
//        try {
//            file.transferTo(target);
//        } catch (IOException e) {
//            e.printStackTrace();
//            return ApiResponse.ofStatus(ApiResponse.Status.INTERNAL_SERVER_ERROR);
//        }
//        return ApiResponse.ofSuccess(null);
    }

    /**
     * 添加房源
     * @param houseForm
     * @param bindingResult
     * @return
     */
    @PostMapping("admin/add/house")
    @ResponseBody
    public ApiResponse addHouse(@ModelAttribute("form-house-add")HouseForm houseForm, BindingResult bindingResult){
        //信息非法状况
        if (bindingResult.hasErrors()){
            //信息不正确就返回一些提示
            return new ApiResponse(HttpStatus.BAD_REQUEST.value(),bindingResult.getAllErrors().get(0).getDefaultMessage(),null);
        }
        //没有封面或者没有图片的情况
        if (houseForm.getPhotos() == null || houseForm.getCover() == null){
            return ApiResponse.ofMessage(HttpStatus.BAD_REQUEST.value(),"必须上传图片");
        }
        //信息校验通过
        //验证是否有这个城市的信息
        Map<SupportAddress.Level, SupportAddressDTO> addressMap = addressService.findCityAndRegion(houseForm.getCityEnName(), houseForm.getRegionEnName());
        if (addressMap.keySet().size() !=2){
            return ApiResponse.ofStatus(ApiResponse.Status.NOT_VALID_PARAM);
        }
        //调用保存方法
        ServiceResult<HouseDTO> result = iHouseService.save(houseForm);
        if (result.isSuccess()){
            return ApiResponse.ofSuccess(result.getResult());
        }
        return ApiResponse.ofSuccess(ApiResponse.Status.NOT_VALID_PARAM);
    }

    /**
     * 展示房源 暂时与user共用同一界面，后续替换
     * @param houseId
     * @param model
     * @return
     */
    @GetMapping("admin/house/show")
    public String show(@RequestParam(value = "id")  Long houseId,
                       Model model){
        if (houseId <=0 ){
            return "404";
        }
        ServiceResult<HouseDTO> serviceResult = iHouseService.findCompleteOne(houseId);
        if (!serviceResult.isSuccess()){
            return "404";
        }

        HouseDTO houseDTO = serviceResult.getResult();
        Map<SupportAddress.Level, SupportAddressDTO> addressMap = addressService.findCityAndRegion(houseDTO.getCityEnName(), houseDTO.getRegionEnName());

        SupportAddressDTO city = addressMap.get(SupportAddress.Level.CITY);
        SupportAddressDTO region = addressMap.get(SupportAddress.Level.REGION);

        model.addAttribute("city",city);
        model.addAttribute("region",region);
        ServiceResult<UserDTO> userDTOServiceResult = userService.findById(houseDTO.getAdminId());
        model.addAttribute("agent",userDTOServiceResult.getResult());
        model.addAttribute("house",houseDTO);

        ServiceResult<Long> result = searchService.aggregateDistrictHouse(city.getEnName(), region.getEnName(), houseDTO.getDistrict());
        //小区在售房源数量统计
        model.addAttribute("houseCountInDistrict",result.getResult());

        return "house-detail";
    }

    /**
     * 编辑房源信息
     * @param id
     * @param model
     * @return
     */
    @GetMapping("admin/house/edit")
    public String houseEditPage(@RequestParam(value = "id") Long id, Model model){
        if (id == null||id<1){
            return "404";
        }
        ServiceResult<HouseDTO> serviceResult = iHouseService.findCompleteOne(id);
        if (!serviceResult.isSuccess()){
            return "404";
        }
        HouseDTO result = serviceResult.getResult();
        model.addAttribute("house",result);
        Map<SupportAddress.Level, SupportAddressDTO> addressMap = addressService.findCityAndRegion(
                result.getCityEnName(), result.getRegionEnName()
        );
        model.addAttribute("city",addressMap.get(SupportAddress.Level.CITY));
        model.addAttribute("region",addressMap.get(SupportAddress.Level.REGION));
        HouseDetailDTO detailDTO = result.getHouseDetail();

        ServiceResult<SubwayDTO> subwayDTOServiceResult = addressService.findSubway(detailDTO.getSubwayLineId());
        if (subwayDTOServiceResult.isSuccess()){
            model.addAttribute("subway",subwayDTOServiceResult.getResult());
        }
        ServiceResult<SubwayStationDTO> subwayStationDTOServiceResult = addressService.findSubwayStation(detailDTO.getSubwayStationId());
        if (subwayStationDTOServiceResult.isSuccess()){
            model.addAttribute("station",subwayStationDTOServiceResult.getResult());
        }
        return "admin/house-edit";
    }

    /**
     * 编辑接口
     * @param houseForm
     * @param bindingResult
     * @return
     */
    @PostMapping("admin/house/edit")
    @ResponseBody
    public ApiResponse saveHouse(@Valid @ModelAttribute("form-house-deit") HouseForm houseForm,BindingResult bindingResult){
         if (bindingResult.hasErrors()){
             return  new ApiResponse(HttpStatus.BAD_REQUEST.value(), bindingResult.getAllErrors().get(0).getDefaultMessage(),null);
         }
        Map<SupportAddress.Level, SupportAddressDTO> addressMap = addressService.findCityAndRegion(houseForm.getCityEnName(), houseForm.getRegionEnName());
         if (addressMap.keySet().size() !=2){
             return ApiResponse.ofSuccess(ApiResponse.Status.NOT_VALID_PARAM);
         }
        ServiceResult result = iHouseService.update(houseForm);

         if (result.isSuccess()){
             //更新成功
             return ApiResponse.ofSuccess(null);
         }
         ApiResponse response = ApiResponse.ofStatus(ApiResponse.Status.BAD_REQUEST);
         response.setMessage(result.getMessage());

        return response;
    }

    /**
     * 移除图片接口
     * @param id
     * @return
     */
    @DeleteMapping("admin/house/photo")
    @ResponseBody
    public ApiResponse removeHousePhoto(@RequestParam(value = "id") Long id) {
        ServiceResult result = this.iHouseService.removePhoto(id);

        if (result.isSuccess()) {
            return ApiResponse.ofStatus(ApiResponse.Status.SUCCESS);
        } else {
            return ApiResponse.ofMessage(HttpStatus.BAD_REQUEST.value(), result.getMessage());
        }
    }

    /**
     * 修改封面接口
     * @param coverId
     * @param targetId
     * @return
     */
    @PostMapping("admin/house/cover")
    @ResponseBody
    public ApiResponse updateCover(@RequestParam(value = "cover_id") Long coverId,
                                   @RequestParam(value = "target_id") Long targetId) {
        ServiceResult result = this.iHouseService.updateCover(coverId, targetId);

        if (result.isSuccess()) {
            return ApiResponse.ofStatus(ApiResponse.Status.SUCCESS);
        } else {
            return ApiResponse.ofMessage(HttpStatus.BAD_REQUEST.value(), result.getMessage());
        }
    }

    /**
     * 增加标签接口
     * @param houseId
     * @param tag 标签内容
     * @return
     */
    @PostMapping("admin/house/tag")
    @ResponseBody
    public ApiResponse addHouseTag(@RequestParam(value = "house_id") Long houseId,
                                   @RequestParam(value = "tag") String tag) {
        if (houseId < 1 || Strings.isNullOrEmpty(tag)) {
            return ApiResponse.ofStatus(ApiResponse.Status.BAD_REQUEST);
        }

        ServiceResult result = this.iHouseService.addTag(houseId, tag);
        if (result.isSuccess()) {
            return ApiResponse.ofStatus(ApiResponse.Status.SUCCESS);
        } else {
            return ApiResponse.ofMessage(HttpStatus.BAD_REQUEST.value(), result.getMessage());
        }
    }

    /**
     * 移除标签接口
     * @param houseId
     * @param tag 标签内容
     * @return
     */
    @DeleteMapping("admin/house/tag")
    @ResponseBody
    public ApiResponse removeHouseTag(@RequestParam(value = "house_id") Long houseId,
                                      @RequestParam(value = "tag") String tag) {
        if (houseId < 1 || Strings.isNullOrEmpty(tag)) {
            return ApiResponse.ofStatus(ApiResponse.Status.BAD_REQUEST);
        }

        ServiceResult result = this.iHouseService.removeTag(houseId, tag);
        if (result.isSuccess()) {
            return ApiResponse.ofStatus(ApiResponse.Status.SUCCESS);
        } else {
            return ApiResponse.ofMessage(HttpStatus.BAD_REQUEST.value(), result.getMessage());
        }
    }

    /**
     * 审核接口可以改变房源状态===包括上架下架删除出租
     * @param id
     * @param operation 操作类型
     * @return
     */
    @PutMapping("admin/house/operate/{id}/{operation}")
    @ResponseBody
    public ApiResponse operateHouse(@PathVariable(value = "id")Long id,
                                    @PathVariable(value = "operation") int operation){
        if (id<=0){
            return ApiResponse.ofStatus(ApiResponse.Status.NOT_VALID_PARAM);
        }
        ServiceResult result;
        switch (operation){
            case HouseOperation.PASS:
                result = this.iHouseService.updateStatus(id, HouseStatus.PASSES.getValue());
                break;
            case HouseOperation.PULL_OUT:
                    result = this.iHouseService.updateStatus(id, HouseStatus.NOT_AUDITED.getValue());
                    break;
            case  HouseOperation.RENT:
                result = this.iHouseService.updateStatus(id, HouseStatus.RENTED.getValue());
                break;
            case  HouseOperation.DELETE:
                result = this.iHouseService.updateStatus(id, HouseStatus.DELETED.getValue());
                break;
            default:
                return ApiResponse.ofStatus(ApiResponse.Status.BAD_REQUEST);
        }
        if (result.isSuccess()){
            return ApiResponse.ofSuccess(null);
        }
        return ApiResponse.ofMessage(HttpStatus.BAD_REQUEST.value(),result.getMessage());
    }


    /**
     * 返回预约管理页面
     * @return
     */
    @GetMapping("admin/house/subscribe")
    public String houseSubscribe(){
        return "admin/subscribe";
    }

    /**
     * 获取用户预约数据
     * @param draw 回显的参数
     * @param start 分页用的，起始位置
     * @param size 一页数量
     * @return
     */
    @GetMapping("admin/house/subscribe/list")
    @ResponseBody
    public ApiResponse subscribeList(@RequestParam(value = "draw") int draw,
                                     @RequestParam(value = "start") int start,
                                     @RequestParam(value = "length") int size){
        //获取
        ServiceMultiResult<Pair<HouseDTO,HouseSubscribeDTO>> result = iHouseService.findSubscribeList(start,size);

        ApiDataTableResponse response = new ApiDataTableResponse(ApiResponse.Status.SUCCESS);
        response.setData(result.getResult());
        response.setDraw(draw);
        response.setRecordsFiltered(result.getTotal());
        response.setRecordsTotal(result.getTotal());
        return response;

    }
}
